package com.jt.safe.base


import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.annotation.LayoutRes
import androidx.fragment.app.Fragment
import androidx.lifecycle.ViewModelProviders
import com.jt.safe.extension.getVmClazz
import com.jt.safe.viewmodel.BaseViewModel
import com.orhanobut.logger.Logger

abstract class BaseFragment<VM : BaseViewModel> : Fragment() {

    lateinit var viewModel: VM
    var isInit = false

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        return inflater.inflate(layoutId, container, false)
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        isInit = true
        viewModel = createViewModel()
        createObserver()
        initView()
    }


    override fun setUserVisibleHint(isVisibleToUser: Boolean) {
        super.setUserVisibleHint(isVisibleToUser)
        loadingData()
    }

    private fun loadingData() {
        if (!isInit) {
            return
        }
        if (userVisibleHint) {
            initData()
        }
    }

    override fun onDestroy() {
        super.onDestroy()
        isInit = false
    }

    private fun createViewModel(): VM {
        return ViewModelProviders.of(this).get(getVmClazz(this) as Class<VM>)
    }
    @get:LayoutRes
    protected abstract val layoutId: Int
    protected abstract fun createObserver()
    abstract fun initView()
    abstract fun initData()
}